package com.topera.msmservice.controller;

import com.topera.commonutils.R;
import com.topera.commonutils.RandomUtil;
import com.topera.msmservice.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edusms/msm")
@CrossOrigin
public class MsmApiController {


    @Autowired
    private MsmService msmService;
    //@Autowired
    //private RedisConfig redisConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @GetMapping("sendMessage/{phone}")
    public R sendMessage(@PathVariable String phone){

        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(redisCode)){

            return R.ok();
        }
        //生成四位随机的验证码
        String code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //发送短信
        boolean sendFlag = msmService.senMessage(param,phone);
        if(sendFlag){
            //存到redis缓存中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//验证码五分钟失效
            return R.ok();
        }else{
            return R.ok().message("短信验证码发送失败");
        }


    }


}
